<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="hcp-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="postForm.sex"
              placeholder="请选择"
              filterable
              clearable
              style="width:100%"
            >
              <el-option
                v-for="item in genderOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="等级" prop="doctorgrade">
            <el-input v-model="postForm.doctorgrade" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="VeevaCode" prop="veevacode">
            <el-input v-model="postForm.veevacode" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="DoctorId" prop="doctorid">
            <el-input v-model="postForm.doctorid" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="省份" prop="provinceCode">
            <el-select
              v-model="postForm.provinceCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeProvince"
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.id"
                :label="item.province_name"
                :value="item.province_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="城市" prop="cityCode">
            <el-select
              v-model="postForm.cityCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeCity"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.city_name"
                :value="item.city_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="医院名称" prop="hospital">
            <el-input v-model="postForm.hospital" disabled />
            <div class="form-tips text-warning">如需修改医院，请先筛选省份和城市。</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!isNoCity" :span="18" :offset="3">
          <el-form-item label="医院" prop="hospid">
            <el-select
              v-model="postForm.hospid"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in hospitalOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="科室" prop="departid">
            <el-select
              v-model="postForm.departid"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in deparpmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getProvince,
  getCities,
  getDepartments,
  getHospitalsByCity
} from '@/api/baseData'
import {
  getHcpUsersList,
  editHcpUser
} from '@/api/hcpUsers'

const defaultForm = {
  id: undefined,
  name: '',
  sex: '',
  doctorgrade: '',
  veevacode: '',
  doctorid: '',
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  hospid: '',
  departid: '',
  hospital: ''
}

export default {
  name: 'HcpUserForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      provinceOptions: [],
      cityOptions: [],
      hospitalOptions: [],
      deparpmentOptions: [],
      genderOptions: [
        {
          name: '男',
          id: 1
        },
        {
          name: '女',
          id: 0
        }
      ],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ]
        // hospid: [
        //   { required: true, message: '请选择医院', trigger: 'change' }
        // ],
        // departid: [
        //   { required: true, message: '请选择科室', trigger: 'change' }
        // ]
      }
    }
  },
  computed: {
    isNoCity() {
      return this._.isEmpty(this.postForm.provinceCode) || this._.isEmpty(this.postForm.cityCode)
    }
  },
  created() {
    this.fetchProvince()
    this.fetchDepartments()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchProvince() {
      getProvince().then(response => {
        // console.log(response)
        this.provinceOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchCities(code) {
      getCities({ provinceCode: code }).then(response => {
        // console.log(response)
        this.cityOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchHospitals() {
      getHospitalsByCity({
        provinceCode: this.postForm.provinceCode,
        cityCode: this.postForm.cityCode
      }).then(response => {
        // console.log(response)
        this.hospitalOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchDepartments() {
      getDepartments().then(response => {
        // console.log(response)
        this.deparpmentOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getHcpUsersList({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.postForm.id = data[0].id
        this.postForm.name = data[0].name
        this.postForm.sex = data[0].sex
        this.postForm.doctorgrade = data[0].doctorgrade
        this.postForm.veevacode = data[0].veevacode
        this.postForm.doctorid = data[0].doctorid
        this.postForm.hospid = data[0].hospid
        this.postForm.departid = data[0].departid
        this.postForm.hospital = data[0].hospital
        if (!this._.isEmpty(data[0].provinceCode)) {
          this.fetchCities(data[0].provinceCode)
          if (!this._.isEmpty(data[0].cityCode)) {
            this.fetchHospitals()
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    changeProvince(province) {
      this.postForm.city = ''
      this.postForm.cityCode = ''
      this.cityOptions = []
      this.postForm.hospid = ''
      this.hospitalOptions = []
      if (this._.isEmpty(province)) {
        this.postForm.province = ''
      } else {
        let provinceObj = {}
        provinceObj = this.provinceOptions.find((item) => {
          return item.province_code === province
        })
        this.postForm.province = provinceObj.province_name
        this.fetchCities(province)
      }
    },
    changeCity(city) {
      this.postForm.hospid = ''
      this.hospitalOptions = []
      if (this._.isEmpty(city)) {
        this.postForm.city = ''
      } else {
        let cityObj = {}
        cityObj = this.cityOptions.find((item) => {
          return item.city_code === city
        })
        this.postForm.city = cityObj.city_name
        this.fetchHospitals()
      }
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.postForm.science = this.postForm.science.join(',')
          this.loading = true
          editHcpUser(this.postForm).then(response => {
            // console.log(response)
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.$router.go(-1)
          }).catch(err => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .hcp-form {
    padding: 40px 140px;
  }
}
</style>
